package com.yuoj.yuojcodesandbox.sandbox.docker;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.yuoj.yuojcodesandbox.CodeSandBox;
import com.yuoj.yuojcodesandbox.dao.DockerDao;
import com.yuoj.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yuoj.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yuoj.yuojcodesandbox.model.ExecuteMessage;
import com.yuoj.yuojcodesandbox.model.JudgeInfo;
import com.yuoj.yuojcodesandbox.model.enums.LanguageImageEnum;
import com.yuoj.yuojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘渠好
 * @since 2025/4/1 22:14
 * docker原生代码沙箱
 */
//@Service
@Slf4j
public class JavaDockerCodeSandbox implements CodeSandBox {
    //存放代码路径
    public static final String TEMP_DIR ="tempCode";

    //统一类名
    public static final String CLASS_MAIN_NAME="Main.java";

    //限制时间
    public static final long LIMIT_MAX_TIME=3000L;

    @Resource
    private DockerDao dockerDao;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        String code = request.getCode();
        List<String> inputList = request.getInput();
        //1.保存代码文件
        String itemPath = System.getProperty("user.dir");
        //保存代码文件
        String codeTempPath=itemPath+ File.separator+TEMP_DIR;
        if (!FileUtil.exist(codeTempPath)) {
            FileUtil.mkdir(codeTempPath);
        }
        //存放代码文件
        String codeParentPath =codeTempPath+File.separator+ UUID.randomUUID();
        String codePath =codeParentPath+File.separator+CLASS_MAIN_NAME;
        File codeFile = FileUtil.writeString(code, codePath, StandardCharsets.UTF_8);

        //2.编译代码
        String compileCmd = String.format("javac -encoding utf-8 %s", codeFile.getAbsolutePath());
        try {
            Process comProcess = Runtime.getRuntime().exec(compileCmd);
            //编译
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(comProcess, "编译");
            if (executeMessage.getExitValue()!=0){
                return ExecuteCodeResponse.builder()
                        .message("编译失败！")
                        .status(2)
                        .build();
            }
        } catch (IOException e) {
            FileUtil.del(codeParentPath);
            return getErrorResponse(e);
        }

        //3.编译好的代码上传到docker容器

        //拉取镜像
        String imageName = LanguageImageEnum.JAVA11.getImage();

        //判断是否有该镜像
        List<String> imageList = dockerDao.getImageList();
        if (!imageList.contains(imageName)){
            try {
                dockerDao.pullImage(imageName);
            }catch (Exception e){
                throw new RuntimeException("拉取镜像失败!");
            }
        }

        //创建容器
        HostConfig hostConfig = new HostConfig();  //docker主机配置
        hostConfig.withMemory(100*1000*1000L);
        hostConfig.withMemorySwap (0L);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(codeParentPath,new Volume("/app")));  //目录挂载
        CreateContainerResponse container = dockerDao.createContainer(imageName, hostConfig);
        String containerId = container.getId();

        //启动容器
        dockerDao.startContainer(containerId);

        //4.执行代码整理输出结果

        //执行内存
        long[] memory={0};

        //执行时间
        long maxTime=0;

        List<String> outPutList = new LinkedList<>();

        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setStatus(1);  //默认是成功的

        for (String args : inputList) {
            String[] arg = args.split(" ");
            String[] runCmd = ArrayUtil.append(new String[]{"java", "-Dfile.encoding=utf-8", "-cp", "/app", "Main"}, arg);
            //创建容器执行命令
            ExecCreateCmdResponse execCreateCmdResponse = dockerDao.CreateExecuteCmd(containerId, runCmd);
            String execId = execCreateCmdResponse.getId();

            StringBuilder message = new StringBuilder();
            StringBuilder errorMessage = new StringBuilder();

            //执行命令回调函数
            ExecStartResultCallback startResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
                    } else {
                        message.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
                    }
                    super.onNext(frame);
                }
            };

            //获取执行内存

            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<>() {


                @Override
                public void close()  {
                    throw new UnsupportedOperationException ();
                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    Long usage = statistics.getMemoryStats().getUsage();
                    if (usage != null) {
                        log.info("占用内存:{}", usage);
                        memory[0] = Math.max((usage/1000000), memory[0]);
                    }
                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            };

            try (ResultCallback<Statistics> callback = dockerDao.stats(containerId, statisticsResultCallback)) {
                //执行创建命令
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();
                dockerDao.execStart(execId, startResultCallback,LIMIT_MAX_TIME, TimeUnit.MILLISECONDS);  //ms
                stopWatch.stop();
                long execTime = (stopWatch.getLastTaskTimeMillis())/1000;
                maxTime = Math.max(execTime, maxTime);
            } catch (Exception e) {
                //执行失败也要删除文件
                FileUtil.del(codeParentPath);
                return getErrorResponse(e);
            }

            if (CharSequenceUtil.isNotBlank(message.toString())) {
                outPutList.add(message.toString().replace("\n", ""));
                log.info("正常输出信息：{}",message);
            }
            if (CharSequenceUtil.isNotBlank(errorMessage.toString())) {
                outPutList=new LinkedList<>();
                log.error("异常执行信息:{}",errorMessage);
                executeCodeResponse.setStatus(3);
                executeCodeResponse.setMessage(errorMessage.toString());
                break;
            }
        }

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(memory[0]);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        executeCodeResponse.setOutput(outPutList);
        //5.清理文件
        FileUtil.del(codeParentPath);

        //删除容器
        dockerDao.deleteContainer(containerId);


        return executeCodeResponse;
    }

    //6.增强程序健壮性

    public ExecuteCodeResponse getErrorResponse(Throwable throwable) {
        return ExecuteCodeResponse.builder()
                .status(2)
                .output(new LinkedList<>())
                .message(throwable.getMessage())
                .judgeInfo(new JudgeInfo())
                .build();

    }
}
